package com.ruoyi.project.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayObject;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.github.binarywang.wxpay.bean.order.WxPayAppOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.ruoyi.common.utils.AlipayConfig;
import com.ruoyi.framework.aspectj.lang.annotation.Ide;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.system.domain.SysOrder;
import com.ruoyi.project.system.service.SysOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import test.util.SequenceUtils;

import java.math.BigDecimal;
import java.util.Map;

@RestController
@RequestMapping("/mobile/system")
public class sysPayController extends BaseController {

    @Autowired
    private SysOrderService sysOrderService;


    @Autowired
    private WxPayService wxPayService;
    @Autowired
    public RedisTemplate redisTemplate;

    @GetMapping("/getPayForm")
    @Ide
    public AjaxResult getPayForm(){

        String result="";
        // 超时时间 可空
        String timeout_express="2m";
        // 销售产品码 必填
        String product_code="QUICK_WAP_WAY";
        /**********************/
        // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
        //调用RSA签名方式，这个不用你管，只要你配置文件是正确的
        AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL,
                AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT,
                AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY,AlipayConfig.SIGNTYPE);
        AlipayTradeWapPayRequest alipay_request=new AlipayTradeWapPayRequest();

        // 封装请求支付信息
        AlipayTradeWapPayModel model=new AlipayTradeWapPayModel();
        //带！的都是你需要传递的参数 其他的是支付宝必须的
        //！本地生成的订单编号
        model.setOutTradeNo(""+System.currentTimeMillis());
        //！商品名称
        model.setSubject("aaaaaa");
        //！商品价格
        model.setTotalAmount("20");
        //！商品介绍
        model.setBody("aaaaaa");
        //超时时间
        model.setTimeoutExpress(timeout_express);
        //产品销售码
        model.setProductCode(product_code);
        //将参数传入到 BizModel中
        alipay_request.setBizModel(model);
        //异步回调地址
        alipay_request.setNotifyUrl(AlipayConfig.notify_url);
        //同步回调地址
        alipay_request.setReturnUrl(AlipayConfig.return_url);
//            String form = "";
        // 调用SDK生成表单
        //get方式生成表单 主要解决在微信中对支付宝屏蔽问题，如果不是在微信中可post提交，将form的注释解开，result注释掉即可
        try {
            result= client.pageExecute(alipay_request,"get").getBody();
            System.out.println(result);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return AjaxResult.success(null,result);
    }
    @RequestMapping(value = "/aliPay", method = RequestMethod.POST)
    public AjaxResult aliPay(@RequestBody Map map){
        Long orderId=Long.valueOf(map.get("orderId")+"");
        SysOrder sysOrder=sysOrderService.queryById(orderId);
        String orderNo =sysOrder.getOrderNo();
        Double money=sysOrder.getMoney();
        //支付宝
        if("1".equals(map.get("payType")+"")){
            // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
            //调用RSA签名方式，这个不用你管，只要你配置文件是正确的
            AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL,
                    AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT,
                    AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY,AlipayConfig.SIGNTYPE);
            AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
            AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
            model.setSubject("颐和生鲜");//标题
            model.setOutTradeNo(orderNo);//商家唯一订单号
            model.setTimeoutExpress("15m");//1分钟没有支付，交易将会关闭
            model.setTotalAmount(money+"");//订单总额
            request.setBizModel(model);
            try {
                AlipayTradeAppPayResponse response  =  client.sdkExecute(request);
                System.out.println(JSONObject.toJSONString(response));
                if(response.isSuccess()){
                    return AjaxResult.success(null,response.getBody());
                }
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
        }else if("2".equals(map.get("payType")+"")){
            //微信支付
            BigDecimal bg = new BigDecimal(money * 100);
            double doubleValue = bg.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
            WxPayUnifiedOrderRequest.WxPayUnifiedOrderRequestBuilder builder = WxPayUnifiedOrderRequest.newBuilder();
            WxPayUnifiedOrderRequest request  = builder.body("颐和生鲜")
                    .totalFee((int)doubleValue).outTradeNo(orderNo)
                    .spbillCreateIp("0.0.0.0")
                    .tradeType("APP").build();
            WxPayAppOrderResult o = null;
            try {
                o = wxPayService.createOrder(request);
            } catch (WxPayException e) {
                e.printStackTrace();
            }
            return AjaxResult.success(o);
        }
        return AjaxResult.error("支付失败");
    }
}
